// pages/message/friends/friends.js
const {
  getFolloweds, unfollow, getUserById
} = require('../../../apis/api')

import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../../store/store'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    MessageList: [

    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['username', 'userAvatar', 'email', 'token'],
      actions: ['setUsername', 'setUserAvatar', 'setEmail', 'setToken'],
    })
  },
  unfollow(e) {
    unfollow(this.data.token, e.currentTarget.dataset.userid, (res) => {
      if (res.data.code === 200) {
        wx.showToast({
          title: '取关成功',
          icon: 'success'
        })
        this.onReady()
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    getFolloweds(this.data.token, (res) => {
      if (res.data.code === 200) {

        var arr = res.data.data.map((item) => {
          return new Promise((resolve) => {
            getUserById(this.data.token, item, (res) => {
              if (res.data.code === 200) {
                resolve({
                  fanId:item,
                  pictureUrl: res.data.data.pictureUrl,
                  name: res.data.data.userName,
                  relation:true
                });
              } else {
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                });
                resolve(item); // Return the original item in case of error.
              }
            });
          });
        });
        Promise.all(arr).then((updatedData) => {
          this.setData({
            MessageList: updatedData,
          });
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    })
  },
  gotoUser(e){
    wx.navigateTo({
      url: '/pages/userDetail/userDetail?id='+e.currentTarget.dataset.userid,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})